package com.watermeter.android.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oa.android.R;
import com.watermeter.android.adapter.YesCBAdapter;
import com.watermeter.android.entry.UpRoute;
import com.watermeter.android.utils.UConstants;
import com.watermeter.android.utils.Util;
import com.watermeter.android.view.SelectDatePopupWindow;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 已抄表表列表
 * 
 * @author -zouqh
 * 
 */
public class YesCBActivity extends Activity implements OnClickListener {

	private ImageView close;
	private TextView title;
    private TextView save,update;
    private ListView listView;
    private YesCBAdapter adapter;
    private List<UpRoute> upRouteList;
    public DbManager.DaoConfig daoConfig;
    ProgressDialog dialog;
    private String filePath;
    private String fileName;
    private Util util;
    private int flag=1;

    private Calendar calendar ;//日历
    private int yeas;//年
    private String mouth;//月
    private String time;
    private List<String> timeArr;
    private SelectDatePopupWindow datePop;
    private String strTime[]=new String[3];
    public  static YesCBActivity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.yes_cb_activity);
		close = (ImageView) findViewById(R.id.close);
		title = (TextView) findViewById(R.id.title_text);
        save = (TextView) findViewById(R.id.ritgh_text);
        update= (TextView) findViewById(R.id.upBtn);
        listView=(ListView)findViewById(R.id.listview);
        activity=this;
		title.setText("已抄表");
        save.setVisibility(View.VISIBLE);
        update.setOnClickListener(this);
		close.setOnClickListener(this);
        save.setOnClickListener(this);
        calendar = Calendar.getInstance();
        yeas=calendar.get(Calendar.YEAR);
        int m=calendar.get(Calendar.MONTH)+1;
        if(m<10){
            mouth="0"+m;
        }else{
            mouth=m+"";
        }
        time=yeas+mouth;
        save.setText(time);
        strTime[0] = Util.getMosOne(yeas, m);
        strTime[1] = time;
        strTime[2] = Util. getNextOne(yeas, m);
        upRouteList=new ArrayList<>();
        selecteDate(time);


            adapter=new YesCBAdapter(this,upRouteList);
            listView.setAdapter(adapter);

        util=new Util(this);
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            flag=0;
            return;
        }
        filePath= Environment.getExternalStorageDirectory().getPath()+ File.separator + "CBFile"+ File.separator ;
        System.out.println("CCCCCCCCCCCCC");
        Util.makeRootDirectory(filePath);
        fileName="uproute.txt";


	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent ;
		switch (v.getId()) {
		case R.id.close:
			finish();
			break;
            case R.id.upBtn:
               if(flag!=0){
                   if (upRouteList!=null&&upRouteList.size()>0){
                       Gson gson = new Gson();
                       String json=gson.toJson(upRouteList);//将更新数组
                       String str="{\"cby\":\""+UConstants.EmpId+"\", \"total\":\""+upRouteList.size()+"\",\"rows\":"+json+"}";
                       util.writeTxtToFile(str,filePath,fileName);
                       UpsRoute(time);
                   }

               }else{
                   Toast.makeText(this,"请先安装SD卡！",Toast.LENGTH_SHORT).show();
               }

                break;
            case R.id.ritgh_text:
                datePop = new SelectDatePopupWindow(this, strTime, save,2);
                datePop.showAsDropDown(v, Gravity.TOP | Gravity.RIGHT, 0,
                        Util.px2dip(this, 70));
                break;

		default:
			break;
		}
	}
    public void setReh(String str){
        time=str;
        upRouteList.clear();
        adapter.notifyDataSetChanged();
        selecteDate(str);
        adapter.notifyDataSetChanged();
    }

    /**
     * 获已抄表数据
     */
    private void selecteDate(String t) {
//
        DbManager manager = x.getDb(daoConfig);
        try {
                List<UpRoute> list= manager.selector(UpRoute.class).where("MOTH","=",t).findAll();
                if (null!=list&&list.size()>0){
                    upRouteList.addAll(list);
                    update.setVisibility(View.VISIBLE);
                }else {
                    update.setVisibility(View.GONE);
                }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //上传抄表路线
    public void UpsRoute(String time) {
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        RequestParams params = new RequestParams(UConstants.UPDATE_DATE);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("SMON", time);
        params.addBodyParameter("CBY", UConstants.EmpId);
        params.addBodyParameter("Total", upRouteList.size()+"");
        params.addBodyParameter("file", new File(filePath+fileName));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_LONG).show();
                          upRouteList.clear();
                           adapter.notifyDataSetChanged();
                            update.setVisibility(View.GONE);
                            deleteDate();
                        } else {
                            Toast.makeText(x.app(), "上传失败！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "上传出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 删除已抄表数据
     */
    private void deleteDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
//            manager.delete(UpRoute.class);
            manager.delete(UpRoute.class, WhereBuilder.b("MOTH", "=",time));
//            upRouteList= manager.selector(UpRoute.class).findAll();
//            System.out.println("upRouteList.size()="+upRouteList.get(0));

        } catch (DbException e) {
            e.printStackTrace();
        }
    }



}
